<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>添加修补记录</title>
  <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
  <style>
    .photo-preview-container {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin-top: 10px;
    }
    .photo-preview {
      position: relative;
      width: 100px;
      height: 100px;
      border-radius: 8px;
      overflow: hidden;
      border: 1px solid #dee2e6;
    }
    .photo-preview img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    .remove-photo {
      position: absolute;
      top: 2px;
      right: 2px;
      background: rgba(0,0,0,0.7);
      color: white;
      border: none;
      border-radius: 50%;
      width: 20px;
      height: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      cursor: pointer;
    }
    .upload-progress {
      margin-top: 10px;
    }
    .progress {
      height: 8px;
    }
  </style>
</head>
<body>
<div class="container mt-4">
  <h1>为轮胎 <span th:text="${tire.tireNumber}"></span> 添加修补记录</h1>

  <!-- 修改表单提交路径，添加 /api 前缀 -->
  <form th:action="@{/api/tires/{id}/repair(id=${tire.id})}" method="post" enctype="multipart/form-data" id="repairForm">
    <div class="mb-3">
      <label for="repairRecord" class="form-label">修补描述</label>
      <textarea class="form-control" id="repairRecord" name="repairRecord" rows="3" required
                placeholder="请详细描述修补的部位、方法和使用的材料等信息"></textarea>
    </div>

    <div class="mb-3">
      <label for="repairMileage" class="form-label">修补时公里数</label>
      <input type="number" class="form-control" id="repairMileage" name="repairMileage"
             th:value="${tire.installMileage}" required min="0">
    </div>

    <div class="mb-3">
      <label for="repairCost" class="form-label">修补费用</label>
      <input type="number" step="0.01" class="form-control" id="repairCost" name="repairCost"
             placeholder="0.00" required min="0">
    </div>

    <!-- 新增照片上传部分 -->
    <div class="mb-3">
      <label for="repairPhotos" class="form-label">修补照片（可选）</label>
      <input type="file" class="form-control" id="repairPhotos" name="repairPhotos"
             multiple accept="image/*" onchange="previewPhotos(this)">
      <small class="text-muted">可上传多张修补前后的照片，支持 JPG、PNG 格式</small>

      <!-- 照片预览区域 -->
      <div class="photo-preview-container" id="photoPreview"></div>

      <!-- 上传进度 -->
      <div class="upload-progress d-none" id="uploadProgress">
        <div class="progress">
          <div class="progress-bar" role="progressbar" style="width: 0%"></div>
        </div>
        <small class="text-muted">上传中...</small>
      </div>
    </div>

    <button type="submit" class="btn btn-primary">添加修补记录</button>
    <!-- 修改取消按钮的返回路径，添加 /api 前缀 -->
    <a th:href="@{/api/tires/{id}(id=${tire.id})}" class="btn btn-secondary">取消</a>
  </form>
</div>

<script>
  // 照片预览功能
  function previewPhotos(input) {
    const previewContainer = document.getElementById('photoPreview');
    previewContainer.innerHTML = '';

    if (input.files && input.files.length > 0) {
      for (let i = 0; i < input.files.length; i++) {
        const file = input.files[i];
        const reader = new FileReader();

        reader.onload = function(e) {
          const previewDiv = document.createElement('div');
          previewDiv.className = 'photo-preview';

          const img = document.createElement('img');
          img.src = e.target.result;
          img.alt = '预览图片';

          const removeBtn = document.createElement('button');
          removeBtn.type = 'button';
          removeBtn.className = 'remove-photo';
          removeBtn.innerHTML = '×';
          removeBtn.onclick = function() {
            previewDiv.remove();
            // 从文件列表中移除对应的文件
            const dt = new DataTransfer();
            const files = input.files;
            for (let j = 0; j < files.length; j++) {
              if (j !== i) {
                dt.items.add(files[j]);
              }
            }
            input.files = dt.files;
          };

          previewDiv.appendChild(img);
          previewDiv.appendChild(removeBtn);
          previewContainer.appendChild(previewDiv);
        };

        reader.readAsDataURL(file);
      }
    }
  }

  // 表单提交处理
  document.getElementById('repairForm').addEventListener('submit', function(e) {
    const files = document.getElementById('repairPhotos').files;
    if (files.length > 0) {
      e.preventDefault();

      const uploadProgress = document.getElementById('uploadProgress');
      const progressBar = uploadProgress.querySelector('.progress-bar');
      uploadProgress.classList.remove('d-none');

      const formData = new FormData(this);

      // 使用XMLHttpRequest提交以便跟踪进度
      const xhr = new XMLHttpRequest();

      xhr.upload.addEventListener('progress', function(e) {
        if (e.lengthComputable) {
          const percentComplete = (e.loaded / e.total) * 100;
          progressBar.style.width = percentComplete + '%';
          progressBar.textContent = Math.round(percentComplete) + '%';
        }
      });

      xhr.addEventListener('load', function() {
        if (xhr.status === 200) {
          // 上传成功，重定向到轮胎详情页面
          window.location.href = document.querySelector('a.btn-secondary').href;
        } else {
          alert('提交失败: ' + xhr.responseText);
          uploadProgress.classList.add('d-none');
        }
      });

      xhr.addEventListener('error', function() {
        alert('提交过程中发生错误');
        uploadProgress.classList.add('d-none');
      });

      xhr.open('POST', this.action);
      xhr.send(formData);
    }
    // 如果没有照片，让表单正常提交
  });
</script>
</body>
</html>